﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SoftwareEngineering.Modeling.DataModeling;
using SoftwareEngineering.Modeling;
using NetFrameworkExtensions;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.Design;

namespace QuickConsoleTests
{
  class Program
  {
    static void Main(string[] args)
    {
      //TestConformKey();
      TestModelValidation();
    }

    private static void TestModelValidation()
    {
      Console.WriteLine("*************** TestModelValidation ***************");
      Console.WriteLine();

      var model = LoadModel();
      //model.EntityTypes[0].Name = "Whatever!";
      var errors = new List<ValidationResult>();
      if (ModelValidator.TryValidate(model, null, errors))
      {
        Console.ForegroundColor = ConsoleColor.Green;
        Console.WriteLine("Model is valid!");
        Console.ForegroundColor = ConsoleColor.Gray;
      }
      else
      {
        Console.ForegroundColor = ConsoleColor.Red;
        Console.WriteLine("Model has validation errors!");
        Console.ForegroundColor = ConsoleColor.Gray;
        foreach (var error in errors)
        {
          Console.WriteLine(error.PrintUnlocalized());
        }
      }
    }

    private static void TestConformKey()
    {
      Console.WriteLine("*************** TestConformKey ***************");
      Console.WriteLine();

      var Model = LoadModel();

      Console.WriteLine("Entity Keys");
      foreach (var entity in Model.EntityTypes)
      {
        var key = entity.ConformKey().ToArray();
        var pairs = key.Select(k => Tup.Create(k.KeyName(), k.KeyType()));
        var keys = pairs.ToStringList(", ", p => string.Format("{0} {1}", p.Item2, p.Item1));
        Console.WriteLine("    Entity {0}: {1}", entity.Name, keys);

        foreach (var refer in entity.References)
        {
          key = refer.ConformKey().ToArray();
          pairs = key.Select(k => Tup.Create(k.KeyName(), k.KeyType()));
          keys = pairs.ToStringList(", ", p => string.Format("{0} {1}", p.Item2, p.Item1));
          Console.WriteLine("        Reference {0}: {1}", refer.Name, keys);
        }
      }

    }

    private static DataModel LoadModel()
    {
      var dir = Environment.CurrentDirectory;
      //var Model = (DataModel)ModelReader.ReadModel(@"..\..\..\SoftwareEngineering.Tests\Data\DataModel.xml");
      var Model = (DataModel)ModelReader.ReadModel(@"..\..\..\DemoApp.Models\DataModel.xml");
      return Model;
    }
  }
}
